package com.youyoulong.framework.util.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.youyoulong.framework.util.ThreadVariableUtil;

public final class FrameworkPublicFilter extends OncePerRequestFilter {

	private static String profile;

	public String getProfile() {
		return profile;
	}

	public void setProfile(String profile) {
		FrameworkPublicFilter.profile = profile;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		ThreadVariableUtil.create().setAttribute(ThreadVariableUtil._currentRequestKey, request);
		// 支持跨域请求
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "Content-Type");

		if (request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME) == null) {
			request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, Locale.getDefault());
			request.getSession().setAttribute(ThreadVariableUtil._sessionLocaleKey, Locale.getDefault().toString());
			request.getSession().setAttribute(ThreadVariableUtil._sessionLanguageKey, Locale.getDefault());
		}
		if (request.getSession().getAttribute(ThreadVariableUtil._sessionLocaleKey) == null) {
			request.getSession().setAttribute(ThreadVariableUtil._sessionLocaleKey, Locale.getDefault().toString());
			request.getSession().setAttribute(ThreadVariableUtil._sessionLanguageKey, Locale.getDefault());
		}

		filterChain.doFilter(request, response);

	}

}
